# -*- coding: utf8 -*-
# Create your views here.
#import outland.list.model as om
from django import forms
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseNotFound
from django.http import Http404
from django.shortcuts import render_to_response
from django.utils import simplejson
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm 
from django.contrib.auth.forms import UserCreationForm
from outland.list.models import Shop,ShopCategory,Menu,MenuCategory,Recommendation
#from outland.poll.forms import OutlandUserCreate
import Image, ImageDraw
unauthMsg = "<h3> Unauthorized Request...<br/> Please <a href='/outland/poll'>Login again</a> </h3>"

def writeLog(msg):
    fout = open('c:/djangoLog.txt','a')
    fout.write(str(msg)+'\n')
    fout.close()

def listMenuJson(request, qShop=''):
    if not request.user.is_authenticated(): return HttpResponse(unauthMsg);
    qShop = unescape(qShop);
    menuList = Menu.objects.filter(shop=Shop.objects.get(name=qShop)).values_list('name',flat=True)
    data = simplejson.dumps({'name_list':list(menuList)},ensure_ascii=False)
    return HttpResponse(data)

def listShopJson(request, qCategory=''):
    if not request.user.is_authenticated(): return HttpResponse(unauthMsg);
    qCategory = unescape(qCategory);
    shopList = Shop.objects.filter(category=ShopCategory.objects.get(name=qCategory)).values_list('name',flat=True)
    data = simplejson.dumps({'name_list':list(shopList)},ensure_ascii=False)
    return HttpResponse(data)

def listCategoryJson(request):
    if not request.user.is_authenticated(): return HttpResponse(unauthMsg);
    cateList = ShopCategory.objects.values_list('name',flat=True)
    cateList = [u'공지사항']+list(cateList)
    data = simplejson.dumps({'name_list':list(cateList)},ensure_ascii=False)
    return HttpResponse(data)

def listShopHtml(request, qCategory=''):
    if not request.user.is_authenticated(): return HttpResponse(unauthMsg);
    if qCategory == u'공지사항':
        return render_to_response('poll/notice.html');
    shopList = Shop.objects.filter(category=ShopCategory.objects.get(name=qCategory))
    return render_to_response('poll/ShopList.html',{'shopList':shopList});

def listMenuHtml(request, qShop=''):
    if not request.user.is_authenticated(): return HttpResponse(unauthMsg);
    oShop = Shop.objects.get(id=int(qShop[5:]));
    menuCategoryList = MenuCategory.objects.filter(shop=oShop).order_by('name');
    recList = Recommendation.objects.filter(user__username=request.user.username, menu__shop=oShop)
    res = []
    for i in menuCategoryList:
        tmp = []
        for j in i.menu_set.all().order_by('name'):
            try:
                rec = recList.get(menu=j)
            except:
                rec = 0
            if not rec or (rec and rec.value==0):
                v = 'dono'
            elif rec.value > 5:
                v = 'yes'
            elif rec.value <= 5:
                v = 'no'
            tmp += [{'name':j.name,'price':j.price,'id':j.id,v:1,'desc':j.desc}]
        res += [{'cont':tmp,'cid':i.id,'cname':i.name}]
    return render_to_response('poll/MenuList.html',{'menu':res, 'oShop':oShop});

def save(request):
    if request.user.is_authenticated() and request.method == 'POST' and request.POST.has_key('value') and request.POST.has_key('shopid') and request.POST.has_key('menuid'):
        try:
            rec = Recommendation.objects.get(user__username=request.user.username, menu__id=int(request.POST['menuid']))
        except:
            u = User.objects.get(username=request.user.username);
            m = Menu.objects.get(id=int(request.POST['menuid']));
            rec = Recommendation(user=u, menu=m);
        if request.POST['value'] == 'dono':
            value = 0;
        elif request.POST['value'] == 'yes':
            value = 8;
        elif request.POST['value'] == 'no':
            value = 3;
        else: value = 0;
        rec.value=value;
        rec.save();
        return HttpResponse('Success');
    else:
        return HttpResponse(unauthMsg);

def join(request):
    if request.method == 'POST' and request.POST.has_key('Join'):
        #회원가입 POST 메세지가 들어왔을 때
        form = UserCreationForm(request.POST)
        res = {}
        for i in request.POST:
            res[i] = request.POST[i]
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect("/outland/poll/")
        return render_to_response('poll/Join.html',{'form': form,})
    form = UserCreationForm()
    return render_to_response('poll/Join.html',{'form': form,})

def listShop(request,qCategory='',qShop=''):
    if request.user.is_authenticated():
        return render_to_response('poll/BasePollAjax.html') 
    else:
        if request.method == 'POST' and request.POST.has_key('Login'):
            #로그인 POST 메세지가 들어왔을 때
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # Correct password, and the user is marked "active"
                auth.login(request, user)
                # Redirect to a success page.
                request.session.SESSION_SAVE_EVERY_REQUEST = True;
                return HttpResponseRedirect("/outland/poll/")
            else:
                # Show an error page
                return HttpResponse("Login failed<meta http-equiv='refresh' content='1; url=/outland/poll'>") 
        else:
            form = AuthenticationForm()
        return render_to_response('poll/Login.html',{'form': form,})

def logout(request):
    auth.logout(request)
    return HttpResponse("Logout Succeeded <meta http-equiv='refresh' content='1; url=/outland/poll'>") 

def errorpage404(request):
    return HttpResponseNotFound("Page Not Found.... <meta http-equiv='refresh' content='1; url=/outland/poll'>");
def errorpage500(request):
    return HttpResponseNotFound("Internal Server Error.... <meta http-equiv='refresh' content='1; url=/outland/poll'>");


def showStatus(request):
    if not request.user.is_staff: return HttpResponse('error');
    cateList = ShopCategory.objects.all()
    menuList = []
    menuObj = Menu.objects.all()
    for i in cateList:
        length = 0;
        shopList = []
        for j in Shop.objects.filter(category=i):
            tempMenu = menuObj.filter(shop=j).order_by('name');
            length += tempMenu.count();
            shopList += [{'shop':j, 'menuList':tempMenu}]
        menuList += [{'cate':i, 'shopList':shopList, 'len':length}]
    user = User.objects.all().order_by('username');
    userReco = []
    reco = Recommendation.objects.all();
    menuNameList = {}
    t = 0
    for i in menuList:
        for j in i['shopList']:
            for k in j['menuList']:
                menuNameList[k.id] = t
                t+=1
    for i in user:
        recoList = ['']*t
        for j in reco.filter(user=i):
            if j.value==0:
                v = 'dono'
            elif j.value > 5:
                v = 'yes'
            elif j.value <= 5:
                v = 'no'    
            recoList[ menuNameList[j.menu_id] ]=v
            
        userReco += [{'user':i, 'recoList':recoList}]

             
    return render_to_response('poll/Status.html', {'menuList':menuList, 'userReco':userReco});

MEDIA_ROOT = "c:/outland/outland/static_media/"

def showStatusImg(request):
    if not request.user.is_staff: return HttpResponse('error');
    cateList = ShopCategory.objects.all()
    menuList = []
    menuObj = Menu.objects.all()
    for i in cateList:
        length = 0;
        shopList = []
        for j in Shop.objects.filter(category=i):
            tempMenu = menuObj.filter(shop=j).order_by('name');
            length += tempMenu.count();
            shopList += [{'shop':j, 'menuList':tempMenu}]
        menuList += [{'cate':i, 'shopList':shopList, 'len':length}]
    user = User.objects.all().order_by('username');
    userReco = []
    reco = Recommendation.objects.all();
    menuNameList = {}
    t = 0
    for i in menuList:
        for j in i['shopList']:
            for k in j['menuList']:
                menuNameList[k.id] = t
                t+=1
    im = Image.new("RGB",(t,user.count()),"White")
    draw = ImageDraw.Draw(im)
    count = 0
    for i in user:
        for j in reco.filter(user=i):
            if j.value==0:
                v = "rgb(100%,100%,100%)" 
            elif j.value > 5:
                v = "rgb(0%,100%,0%)"
            elif j.value <= 5:
                v = "rgb(100%,0%,0%)"
            draw.point((menuNameList[j.menu_id],count),v)
        count +=1
    im.save(MEDIA_ROOT+request.user.username+"_status.png","PNG")
    return render_to_response('poll/StatusImg.html', {'img':request.user.username+"_status.png"});

def showStatusTxt(request):
    if not request.user.is_staff: return HttpResponse('error');
    cateList = ShopCategory.objects.all()
    menuList = []
    menuObj = Menu.objects.all()
    for i in cateList:
        length = 0;
        shopList = []
        for j in Shop.objects.filter(category=i):
            tempMenu = menuObj.filter(shop=j).order_by('name');
            length += tempMenu.count();
            shopList += [{'shop':j, 'menuList':tempMenu}]
        menuList += [{'cate':i, 'shopList':shopList, 'len':length}]
    user = User.objects.all().order_by('username');
    userReco = []
    reco = Recommendation.objects.all();
    menuNameList = {}
    t = 0
    for i in menuList:
        for j in i['shopList']:
            for k in j['menuList']:
                menuNameList[k.id] = t
                t+=1
    
    res =[]
    count = 0
    for i in user:
        r = [0]*t
        for j in reco.filter(user=i):
            if j.value==0:
                v = 0 
            elif j.value > 5:
                v = 1 
            elif j.value <= 5:
                v = -1
            r[menuNameList[j.menu_id]]=v
        res += [r]
    st = ''
    for i in res:
        for j in i:
            st+='%3i'%j
        st+='\n'

    response = HttpResponse(st, mimetype='text/plain')
    response['Content-Disposition'] = 'attachment; filename=status.txt'
    return response;

